package com

import (
	model "beergo/app/sys/models"
	"beergo/conf/const/code"
	"beergo/lib/base/controller"
	"beergo/lib/event"
	"beergo/lib/tool"
	"encoding/base64"
	"fmt"
	"github.com/beego/beego/v2/server/web"
	"time"
)

type RegController struct {
	controller.ContainerController
	UserRepository *model.UserRepository
	UserModel      *model.User
	JsonData       map[string]interface{}
}

func (this *RegController) Prepare() {
	this.UserRepository = new(model.UserRepository)
	this.UserModel = new(model.User)
	this.JsonData = map[string]interface{}{}
}

func init() {
	web.Router("/reg", &RegController{}, "*:RegAction")
	web.Router("/reg_sms", &RegController{}, "*:RegSmsAction")
}

func (this *RegController) RegAction() {
	var data = &struct {
		Account string `json:"account"`
		Password string `json:"password"`
		PasswordAg string `json:"passwordAg"`
		Code string `json:"code"`
	}{}

	err:=this.FillModel(data)
	if err != nil {
		this.AnaliseErrors(err)
	}

	find := this.UserRepository.FindOneBy(tool.M{"phone":data.Account},nil)
	if find.Id != 0 {
		this.StopError(code.Error,"账号已注册","")
	}

	if data.Password != data.PasswordAg {
		this.StopError(code.Error,"两次输入的密码不一致","")
	}

	//创建用户
	user:=new(model.User)
	user.Account = data.Account
	user.Phone = data.Account
	user.Password = data.Password
	_,err=user.Save()
	if err != nil {
		this.AnaliseErrors(err)
	}

	//find标识账号信息，
	this.JsonData["account"] = user
	//发出登录事件，需要处理的监听器在JsonData中添加个系统的返回
	event.DispatchToMany("Login", this.JsonData,this.Ctx)
	//this.JsonData["account"] =  user
	this.ReturnSuccess("注册成功", this.JsonData)
}
func (this *RegController) RegSmsAction() {
	var data = &struct {
		Phone string `json:"phone"`
		Code string `json:"code"`
		Account string `json:"account"`
		Password string `json:"password"`
	}{}

	err:=this.FillModel(data)
	if err != nil {
		this.AnaliseErrors(err)
	}

	smsCode ,err := this.GetCacheString("sms_code")
	if err != nil {
		this.StopError(code.Error,"验证码过期","")
	}


	if data.Code != smsCode {
		this.StopError(code.Error,"验证码有误",smsCode)
	}
	find := this.UserRepository.FindOneBy(tool.M{"phone":data.Phone},nil)
	if find.Id != 0 {
		this.StopError(code.Error,"账号已注册","")
	}

	//获取账号
	if data.Account == "" {
		data.Account = data.Phone
	}
	if data.Password == "" {
		data.Password = "123456"
	}
	//创建用户
	user:=new(model.User)
	user.Account = data.Account
	user.Phone = data.Phone
	user.Password = data.Password
	vi:=web.AppConfig.DefaultString("vi","123456")
	token := tool.AesEncrypt(fmt.Sprintf("user %d vi %d",find.Id,time.Now().Unix()),vi)
	tk:=base64.StdEncoding.EncodeToString([]byte(token))
	println(tk)
	user.Token = tk
	_,err=user.Save()
	if err != nil {
		this.AnaliseErrors(err)
	}

	//find标识账号信息，
	this.JsonData["account"] = user
	//发出登录事件，需要处理的监听器在JsonData中添加个系统的返回
	event.DispatchToMany("Login", this.JsonData,this.Ctx)
	//this.JsonData["account"] =  user
	this.ReturnSuccess("注册成功", this.JsonData)
}